<template>
  <div class="ranking_wrap safe" v-if="playerList.length">
    <div class="first_wrap">
      <div class="title">排行榜</div>
      <div class="item_box" @click="handleGoTo(playerList[0])">
        <van-image fit="cover" :src="require('../../assets/images/01.png')" />
        <div class="number">{{ playerList[0].number }}</div>
        <div class="vc">{{ playerList[0].vc }}</div>
        <div class="btn_img" @click.stop="handleVoteSingle(playerList[0])">
          <img src="../../assets/images/1.png" alt="" />
        </div>
        <div class="coverLink">
          <van-image
            fit="cover"
            :src="
              playerList[0].coverType === 'IMAGE' && playerList[0].coverLink
                ? playerList[0].coverLink
                : require('../../assets/images/cover.png')
            "
          />
        </div>
      </div>
    </div>
    <div class="player_list_wrap" v-if="playerList.length > 1">
      <div v-for="(item, index) in playerList" :key="index">
        <template v-if="index != 0">
          <div
            class="item_wrap"
            @click="handleGoTo(item)"
            :style="{ backgroundImage: 'url(' + item.bgLink + ')' }"
          >
            <div
              class="title"
              :class="{ other_title: index === 1 || index === 2 }"
            >
              名称 <span>{{ item.name }}</span>
            </div>
            <div class="number">编号：{{ item.number }}</div>
            <div class="vc">票数：{{ item.vc }}</div>
            <div class="avatar_wrap">
              <van-image
                fit="cover"
                :src="
                  item.coverType === 'IMAGE' && item.coverLink
                    ? item.coverLink
                    : require('../../assets/images/cover.png')
                "
              />
            </div>
            <div class="btn_wrap"  @click.stop="handleVoteSingle(item)">
              <img
                v-if="index == 1"
                src="../../assets/images/btn2.png"
                alt=""
              />
              <img
                v-else-if="index == 2"
                src="../../assets/images/3.png"
                alt=""
              />
              <img v-else src="../../assets/images/4.png" alt="" />
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 已选项 -->
    <div class="choice" v-if="contestantIds.length">
      <div class="choice_wrap">
        <div class="choice-left" v-if="rule.type == 'MULTIPLE_CHOICE'">
          已选<span :style="{color: basic.theme || cfg.theme}">{{contestantIds.length}}</span>项
          ，最少<span :style="{color: basic.theme || cfg.theme}">{{rule.typeMultipleChoiceMinValue}}</span>项
          ，最多<span :style="{color: basic.theme || cfg.theme}">{{rule.typeMultipleChoiceMaxValue}}</span>项
        </div>
        <div class="choice-left" v-if="rule.type == 'REQUIRED_CHOICE'">
          已选<span :style="{color: basic.theme || cfg.theme}">{{contestantIds.length}}</span>项
          ，必须选择<span :style="{color: basic.theme || cfg.theme}">{{rule.typeRequiredChoiceValue}}</span>项
        </div>
        <div
          @click="handleVote"
          :style="{
            background: basic.theme || cfg.theme,
          }"
          class="choice-right"
        >
          <span class="iconfont iconicon-test"></span>
          <span style="margin-left: 4px">{{ voteInfo.type }}</span>
        </div>
      </div>
    </div>
    <footer-logo></footer-logo>
    <van-dialog
      v-model="showWeChatCode"
      title="提示"
      show-cancel-button
      :show-confirm-button="false"
      cancelButtonText="关闭"
      @close="handleClose"
    >
      <div id="qrWeChatCode">
        <img style="width: 140px; height: 140px" :src="wechatCodeQR" alt="" />
        <span>请先扫码关注公众号后操作</span>
      </div>
    </van-dialog>
    <van-dialog
      v-model="showVerfyCode"
      title="验证码"
      :confirm-button-text="$route.query.type"
      show-cancel-button
      @confirm="handleConfirm"
      @close="codeImage.code = ''"
    >
      <div class="verfyCode_wrap">
        <div class="input">
          <van-field
            maxlength="4"
            v-model="codeImage.code"
            placeholder="请输入验证码"
            :error-message="codeImage.errorCode"
          />
        </div>
        <div class="img">
          <img :src="codeImage.url" alt="" />
        </div>
      </div>
    </van-dialog>
    <van-dialog
      v-model="votedConfig.showVoted"
      :title="votedConfig.votedText"
      show-cancel-button
      cancelButtonText="关闭"
      confirmButtonText="去看看"
      @close="handleCloseVoted"
      @confirm="handleConfirmVoted"
      className="votedLink"
    >
      <div>
        <div v-if="votedConfig.tips" class="votedTips">
          {{ votedConfig.tips }}
        </div>
        <div class="link_wrap" v-if="ad.votingLink">
          <van-image fit="cover" :src="ad.votingLink.link" />
        </div>
      </div>
    </van-dialog>
  </div>
</template>
<script>
import footerLogo from "@/components/footerLogo";
import { mapGetters } from "vuex";
import cfg from "@/config";
import { LgetItem,LsetItem } from "@/utils/storage";
import { isWeiXin } from "@/utils/index";
import { wx,wxInit } from "@/utils/jssdkInit";
import axios from "axios";
import { formatDate } from "@/filter";
export default {
  components: {
    footerLogo,
  },
  data() {
    return {
      voteId:LgetItem("voteId"),
      query: {
        pageNum: 1,
        pageSize: 10,
        voteId: LgetItem("voteId"),
      },
      playerList: [],
      authFollowed: false,
      showWeChatCode: false,
      wechatCodeQR: `${cfg.host}${
        cfg.baseUrl
      }/wx/qr-code/get-q-r-code?voteId=${LgetItem("voteId")}`,
      showVerfyCode: false,
      codeImage: {
        url: "",
        logicId: "",
        code: "",
        errorCode: "",
      },
      votedConfig: {
        showVoted: false,
        votedText: "投票成功",
        tips: "",
      },
      current:{},
      voteInfo:{},
      contestantIds: [],
    };
  },
  created() {
    this.isAuth();
    this.getRankingList();
    this.getVoteInfo();
  },
  mounted(){
    this.shareFn(this.share)
  },
  computed: {
    ...mapGetters("configs", {
      ad: "ad",
      basic: "basic",
      commentary: "commentary",
      page: "page",
      wechat: "wechat",
      security: "security",
      rule:'rule',
      share:'share'
    }),
  },
  methods: {
    handleGoTo(item){
      console.log(item)
       if (this.page.contestantListComponent.element.DETAIL_LINK) {
        console.log(item);
        //进入选手详情之前需要收集该选手的访问记录
        LsetItem("cid", item.id);
        axios
          .get(
            `/vote/statistic/visit/report/${LgetItem("voteId")}/${LgetItem(
              "cid"
            )}`
          )
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
        this.$router.push({
          path: "/detail",
          query: {
            playerId: item.id,
          },
        });
      }
    },
    shareFn(share) {
      this.$nextTick(() => {
        wxInit()
          .then(() => {
            wx.updateAppMessageShareData({
              //分享到朋友
              title: share.title, // 分享标题
              desc: share.context, // 分享描述
              link: window.location.href.indexOf('?') != -1?window.location.href:`${window.location.href}?id=${LgetItem("voteId")}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl:share.imageLink?share.imageLink:cfg.shareImg, // 分享图标
              success: () => {
                console.log("分享成功");
              },
            });
            wx.updateTimelineShareData({
              //分享到朋友圈
              title: share.title, // 分享标题
              link: window.location.href.indexOf('?') != -1?window.location.href:`${window.location.href}?id=${LgetItem("voteId")}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl:share.imageLink?share.imageLink:cfg.shareImg, // 分享图标
              success: function () {
                console.log("分享成功");
              },
            });
          })
          .catch((err) => {
            console.log(err,'err');
          });
        //   toast.clear();
      });
    },
    getVoteInfo() {
      this.$api("vote.getVoteInfo", {
        id: this.voteId,
      }).then((res) => {
        this.voteInfo = res;
      });
    },
    handleClose() {
      this.isAuth();
    },
    //是否关注公众号
    isAuth() {
      this.$api("sign.isAuth").then((res) => {
        this.authFollowed = res;
      });
    },
    //输入验证码点击确定提交投票
    handleConfirm() {
      if (this.codeImage.code && this.codeImage.code.length < 4) {
        this.codeImage.errorCode = "请输入4位验证码";
      } else if (!this.codeImage.code) {
        this.codeImage.errorCode = "请输入验证码";
      } else {
        let query = {
          code: this.codeImage.code,
          contestantIds: [this.current.id],
          logicId: this.codeImage.logicId,
        };
        this.submitVote(query);
      }
    },
    // handleVote(item) {
    //   this.current = item;
    //   if (isWeiXin()) {
    //     //是否需要关注公众号才能投票、
    //     if (this.rule.followedVoting) {
    //       console.log("开启了关注公众号");
    //       //判断当前微信号是否已经关注了关注
    //       if (this.authFollowed) {
    //         console.log("已经关注了关注");
    //         //防刷票设置，是否需要验证码
    //         if (this.security.verificationCodeEnabled) {
    //           console.log("需要验证码");
    //           this.getVerfyCode();
    //         } else {
    //           let query = {
    //             code: "",
    //             contestantIds: [item.id],
    //             logicId: "",
    //           };
    //           this.submitVote(query);
    //         }
    //       } else {
    //         //弹出公众号二维码让用户去关注
    //         console.log("弹出公众号二维码让女用户管住");
    //         this.showWeChatCode = true;
    //       }
    //     } else {
    //       if (this.security.verificationCodeEnabled) {
    //         console.log("需要验证码");
    //         this.getVerfyCode();
    //       } else {
    //         let query = {
    //           code: "",
    //           contestantIds: [item.id],
    //           logicId: "",
    //         };
    //         this.submitVote(query);
    //       }
    //     }
    //   } else {
    //     //弹出活动二维码
    //     this.getVoteCoQR();
    //   }
    // },
    //获取验证码
    getVerfyCode() {
      this.$api("vote.getVerfycode").then((res) => {
        this.codeImage.url = res.data;
        this.codeImage.logicId = res.logicId;
        this.showVerfyCode = true;
      });
    },
    handleVoteSingle(item) {
      this.current = item;
      console.log(item);
      /**
       * 点击投票
       * 1.防刷票可以开启投票时间段，只能在这个时间段内投票
       * 2.判断是单选还是多选，还是必选，如果是单选直接判断微信环境，否则将已选项存起来，页面展示已选项choice
       * 3.防刷票，是否需要验证码
       * 4.投票成功
       *
       */
      // 点击投票之前要判断当前是单选，多选还是必选
      // 再判断是微信环境

      //是否开启时间段内投票
      if (this.security.limitDailyVotingTimeEnabled) {
        //当前时间是否在时间段内
        let limitBegin = new Date(
          formatDate(new Date(), "YYYY-MM-DD") +
            " " +
            this.security.limitDailyVotingTimeOnBeginValue
        ).getTime();
        let limitEnd = new Date(
          formatDate(new Date(), "YYYY-MM-DD") +
            " " +
            this.security.limitDailyVotingTimeOnEndValue
        ).getTime();
        let now = new Date().getTime();
        if (now >= limitBegin && now <= limitEnd) {
          if (this.rule.type == "SINGLE_CHOICE") {
            if (isWeiXin()) {
              //是否需要关注公众号才能投票、
              if (this.rule.followedVoting) {
                console.log("开启了关注公众号");
                //判断当前微信号是否已经关注了关注
                if (this.authFollowed) {
                  console.log("已经关注了关注");
                  //防刷票设置，是否需要验证码
                  if (this.security.verificationCodeEnabled) {
                    console.log("需要验证码");
                    this.getVerfyCode();
                  } else {
                    let query = {
                      code: "",
                      contestantIds: [item.id],
                      logicId: "",
                    };
                    this.submitVote(query);
                  }
                } else {
                  //弹出公众号二维码让用户去关注
                  console.log("弹出公众号二维码让女用户管住");
                  this.showWeChatCode = true;
                }
              } else {
                if (this.security.verificationCodeEnabled) {
                  console.log("需要验证码");
                  this.getVerfyCode();
                } else {
                  let query = {
                    code: "",
                    contestantIds: [item.id],
                    logicId: "",
                  };
                  this.submitVote(query);
                }
              }
            } else {
              //弹出活动二维码
              this.getVoteCoQR();
            }
          } else {
            //判断contestantIds是否已经有当前选手了,有移除，无添加
            let index = this.contestantIds.indexOf(item.id);
            if (index != -1) {
              this.contestantIds.splice(index, 1);
            } else {
              if (this.rule.type == "MULTIPLE_CHOICE") {
                // typeMultipleChoiceMinValue;
                // typeMultipleChoiceMaxValue;
                if (
                  this.contestantIds.length >=
                  this.rule.typeMultipleChoiceMaxValue
                ) {
                  this.$toast(
                    `最多可选择${this.rule.typeMultipleChoiceMaxValue}项`
                  );
                } else {
                  this.contestantIds.push(item.id);
                }
              }
              if (this.rule.type == "REQUIRED_CHOICE") {
                if (
                  this.contestantIds.length >= this.rule.typeRequiredChoiceValue
                ) {
                  this.$toast(
                    `最多可选择${this.rule.typeRequiredChoiceValue}项`
                  );
                } else {
                  this.contestantIds.push(item.id);
                }
              }
            }
          }
        } else {
          //提示用户该时间段内不可投票
          this.$toast(`当前时间不可${this.voteInfo.type}`);
        }
      } else {
        if (this.rule.type == "SINGLE_CHOICE") {
          if (isWeiXin()) {
            //是否需要关注公众号才能投票、
            if (this.rule.followedVoting) {
              console.log("开启了关注公众号");
              //判断当前微信号是否已经关注了关注
              if (this.authFollowed) {
                console.log("已经关注了关注");
                //防刷票设置，是否需要验证码
                if (this.security.verificationCodeEnabled) {
                  console.log("需要验证码");
                  this.getVerfyCode();
                } else {
                  let query = {
                    code: "",
                    contestantIds: [item.id],
                    logicId: "",
                  };
                  this.submitVote(query);
                }
              } else {
                //弹出公众号二维码让用户去关注
                console.log("弹出公众号二维码让女用户管住");
                this.showWeChatCode = true;
              }
            } else {
              if (this.security.verificationCodeEnabled) {
                console.log("需要验证码");
                this.getVerfyCode();
              } else {
                let query = {
                  code: "",
                  contestantIds: [item.id],
                  logicId: "",
                };
                this.submitVote(query);
              }
            }
          } else {
            //弹出活动二维码
            this.getVoteCoQR();
          }
        } else {
          //判断contestantIds是否已经有当前选手了,有移除，无添加
          let index = this.contestantIds.indexOf(item.id);
          if (index != -1) {
            this.contestantIds.splice(index, 1);
          } else {
            if (this.rule.type == "MULTIPLE_CHOICE") {
              // typeMultipleChoiceMinValue;
              // typeMultipleChoiceMaxValue;
              if (
                this.contestantIds.length >=
                this.rule.typeMultipleChoiceMaxValue
              ) {
                this.$toast(
                  `最多可选择${this.rule.typeMultipleChoiceMaxValue}项`
                );
              } else {
                this.contestantIds.push(item.id);
              }
            }
            if (this.rule.type == "REQUIRED_CHOICE") {
              if (
                this.contestantIds.length >= this.rule.typeRequiredChoiceValue
              ) {
                this.$toast(`最多可选择${this.rule.typeRequiredChoiceValue}项`);
              } else {
                this.contestantIds.push(item.id);
              }
            }
          }
        }
      }
    },
    handleVote() {
      //既然能够显示已选项，就不用考虑时间范围了
      console.log(this.contestantIds);
      //需要考虑已选项是否符合规则
      if (this.rule.type == "MULTIPLE_CHOICE") {
        if (this.contestantIds.length >= this.rule.typeMultipleChoiceMinValue) {
          if (isWeiXin()) {
            //是否需要关注公众号才能投票、
            if (this.rule.followedVoting) {
              console.log("开启了关注公众号");
              //判断当前微信号是否已经关注了关注
              if (this.authFollowed) {
                console.log("已经关注了关注");
                //防刷票设置，是否需要验证码
                if (this.security.verificationCodeEnabled) {
                  console.log("需要验证码");
                  this.getVerfyCode();
                } else {
                  let query = {
                    code: "",
                    contestantIds: this.contestantIds,
                    logicId: "",
                  };
                  this.submitVote(query);
                }
              } else {
                //弹出公众号二维码让用户去关注
                console.log("弹出公众号二维码让女用户管住");
                this.showWeChatCode = true;
              }
            } else {
              if (this.security.verificationCodeEnabled) {
                console.log("需要验证码");
                this.getVerfyCode();
              } else {
                let query = {
                  code: "",
                  contestantIds: this.contestantIds,
                  logicId: "",
                };
                this.submitVote(query);
              }
            }
          } else {
            //弹出活动二维码
            this.getVoteCoQR();
          }
        } else {
          console.log(111);
          this.$toast(`最少${this.rule.typeMultipleChoiceMinValue}项`);
        }
      }
      if (this.rule.type == "REQUIRED_CHOICE") {
        if (this.contestantIds.length == this.rule.typeRequiredChoiceValue) {
          if (isWeiXin()) {
            //是否需要关注公众号才能投票、
            if (this.rule.followedVoting) {
              console.log("开启了关注公众号");
              //判断当前微信号是否已经关注了关注
              if (this.authFollowed) {
                console.log("已经关注了关注");
                //防刷票设置，是否需要验证码
                if (this.security.verificationCodeEnabled) {
                  console.log("需要验证码");
                  this.getVerfyCode();
                } else {
                  let query = {
                    code: "",
                    contestantIds: this.contestantIds,
                    logicId: "",
                  };
                  this.submitVote(query);
                }
              } else {
                //弹出公众号二维码让用户去关注
                console.log("弹出公众号二维码让女用户管住");
                this.showWeChatCode = true;
              }
            } else {
              if (this.security.verificationCodeEnabled) {
                console.log("需要验证码");
                this.getVerfyCode();
              } else {
                let query = {
                  code: "",
                  contestantIds: this.contestantIds,
                  logicId: "",
                };
                this.submitVote(query);
              }
            }
          } else {
            //弹出活动二维码
            this.getVoteCoQR();
          }
        } else {
          console.log(222);
          this.$toast(`必须选择${this.rule.typeRequiredChoiceValue}项`);
        }
      }
    },
    //提交投票
    submitVote(query) {
      this.$api("vote.submitVote", {
        ...query,
        voteId: this.voteId,
      })
        .then((res) => {
          console.log(res);
          this.getRankingList();
          //投票成功之后，判断是否有投票提示广告
          if (this.ad.votingLinkEnabled) {
            this.votedConfig.showVoted = true;
            this.votedConfig.votedText = `${this.voteInfo.type}成功`;
          } else {
            console.log(`${this.voteInfo.type}成功`)
            this.$notify({ type: 'success', message: `${this.voteInfo.type}成功` });
          }
          this.contestantIds = [];
          
        })
        .catch((err) => {
          console.log(err);
          if (this.ad.votingLinkEnabled) {
            this.votedConfig.showVoted = true;
            this.votedConfig.votedText = `${this.voteInfo.type}失败`;
            this.votedConfig.tips = err.desc;
          } else {
            this.$notify({
              type: "danger",
              message: err.desc,
            });
          }
        });
    },
    getRankingList() {
      this.$api("player.getRankingList", this.query).then((res) => {
        res.data.forEach((item, index) => {
          switch (index) {
            case 1:
              item.bgLink = require("../../assets/images/02.png");
              break;
            case 2:
              item.bgLink = require("../../assets/images/03.png");
              break;
            case 3:
              item.bgLink = require("../../assets/images/04.png");
              break;
            case 4:
              item.bgLink = require("../../assets/images/05.png");
              break;
            case 5:
              item.bgLink = require("../../assets/images/06.png");
              break;
            case 6:
              item.bgLink = require("../../assets/images/07.png");
              break;
            case 7:
              item.bgLink = require("../../assets/images/08.png");
              break;
            case 8:
              item.bgLink = require("../../assets/images/09.png");
              break;
            case 9:
              item.bgLink = require("../../assets/images/10.png");
              break;
            default: {
              break;
            }
          }
        });
        this.playerList = res.data;
        console.log(this.playerList);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.ranking_wrap {
  width: 100%;
  min-height: 100vh;
  position: relative;
  .choice {
    position: fixed;
    bottom: calc(50px + constant(safe-area-inset-bottom));
    bottom: calc(50px + env(safe-area-inset-bottom));
    left: 0;
    width: 100%;
    .choice_wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #fff;
      padding: 0 10px;
      box-sizing: border-box;
      width: 100%;
      height: 42px;
      .choice-left {
        font-size: 12px;
        color: #797979;
      }
      .choice-right {
        font-size: 14px;
        color: #fff;
        padding: 5px 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 2px;
      }
    }
  }
  .first_wrap {
    height: 262px;
    background-image: url("../../assets/images/rankingBg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .title {
      font-size: 18px;
      color: #fff;
      margin-top: 30px;
    }
    .item_box {
      font-size: 0;
      position: relative;
      ::v-deep.van-image {
        width: 330px;
        height: auto;
      }
      .number {
        position: absolute;
        font-size: 14px;
        top: 72px;
        left: 202px;
      }
      .vc {
        font-size: 16px;
        position: absolute;
        top: 92px;
        left: 202px;
      }
      .btn_img {
        position: absolute;
        top: 113px;
        left: 170px;
        img {
          width: 80px;
          height: auto;
        }
      }
      .coverLink {
        position: absolute;
        width: 80px;
        height: 80px;
        top: 70px;
        left: 75px;
        ::v-deep.van-image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .player_list_wrap {
    background-color: #fff;
    margin: 10px;
    padding: 15px 5px;
    border-radius: 4px;
    .item_wrap {
      width: 100%;
      height: 138px;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      margin-bottom: 10px;
      position: relative;
      .title {
        position: absolute;
        left: 75px;
        top: 20px;
        font-size: 16px;
      }
      .other_title {
        top: 28px;
      }
      .number {
        position: absolute;
        font-size: 14px;
        left: 110px;
        top: 65px;
      }
      .vc {
        position: absolute;
        font-size: 14px;
        left: 110px;
        top: 95px;
      }
      .avatar_wrap {
        position: absolute;
        width: 80px;
        height: 80px;
        top: 50px;
        left: 15px;
        ::v-deep.van-image {
          width: 100%;
          height: 100%;
        }
      }
      .btn_wrap {
        position: absolute;
        right: 10px;
        bottom: 10px;
        img {
          width: 80px;
          height: auto;
        }
      }
    }
  }
  #qrWeChatCode {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    flex-direction: column;
    span {
      margin-top: 15px;
      color: #999;
      font-size: 12px;
    }
  }
  .verfyCode_wrap {
    padding: 20px 0;
    display: flex;
    align-items: center;
    .input {
      flex: 1;
    }
    .img {
      flex: 1;
      text-align: center;
      img {
        width: 100px;
        height: 44px;
      }
    }
  }
  .votedLink {
    ::v-deep.van-dialog__header {
      color: #fb4723;
    }
    .votedTips {
      font-size: 12px;
      color: #999;
      text-align: center;
      line-height: 22px;
    }
    .link_wrap {
      width: 100%;
      height: 250px;
      font-size: 0;
      margin-top: 8px;
    }
    ::v-deep.van-image {
      width: 100%;
      height: 100%;
    }
  }
}
</style>